<template>
  <div class="mod-config">
    <el-form
      :inline="true"
      :model="dataForm"
      @keyup.enter.native="getDataList()"
    >
      <el-form-item>
        <el-input
          v-model="dataForm.key"
          placeholder="订单号/姓名/地址/手机号"
          clearable
          style="width: 200px"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <!-- 订单状态选择 -->
        <el-select
          v-model="query.orderStatus"
          filterable
          clearable
          placeholder="订单状态"
          style="width: 150px"
        >
          <el-option
            v-for="item in $enums.orderStatusEnum"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 收货状态选择 -->
      <el-form-item>
        <el-select
          v-model="query.orderConfirmStatus"
          filterable
          clearable
          placeholder="收货状态"
          style="width: 150px"
        >
          <el-option
            v-for="item in $enums.orderConfirmReceivingEnum"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <!-- 时间 -->
        <el-date-picker
          v-model="query.startAndEndTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <!-- <el-button
          v-if="isAuth('sys:order:save')"
          type="primary"
          @click="addOrUpdateHandle()"
          >新增</el-button
        > -->
        <!-- <el-button v-if="isAuth('sys:order:delete')" type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button> -->
        <el-button
          v-if="isAuth('sys:order:info')"
          type="primary"
          @click="showOrderDetail()"
          :disabled="dataListSelections.length != 1"
          >查看订单明细</el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      :stripe="true"
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%"
    >
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50"
      >
      </el-table-column>
      <el-table-column
        prop="id"
        header-align="center"
        align="center"
        label="ID"
      >
      </el-table-column>
      <el-table-column
        prop="orderSn"
        header-align="center"
        align="center"
        label="订单号"
        width="120"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <el-table-column
        prop="receiverName"
        header-align="center"
        align="center"
        label="收货人姓名"
      >
      </el-table-column>
      <el-table-column
        prop="receiverDetailAddress"
        header-align="center"
        align="center"
        label="收货人详细地址"
      >
      </el-table-column>
      <el-table-column
        prop="receiverPhone"
        header-align="center"
        align="center"
        label="收货人手机号"
      >
      </el-table-column>
      <el-table-column
        prop="orderStatusChinese"
        header-align="center"
        align="center"
        label="订单状态"
      >
      </el-table-column>
      <el-table-column
        prop="orderConfirmStatusChinese"
        header-align="center"
        align="center"
        label="确认收货状态"
      >
      </el-table-column>
      <el-table-column
        prop="orderRefundStatusChinese"
        header-align="center"
        align="center"
        label="退款状态"
      >
      </el-table-column>
      <el-table-column
        prop="remark"
        header-align="center"
        align="center"
        label="订单备注"
      >
      </el-table-column>
      <el-table-column
        prop="createTime"
        header-align="center"
        align="center"
        label="创建时间"
        :formatter="tableTimeFormatter"
      >
      </el-table-column>
      <el-table-column
        prop="updateTime"
        header-align="center"
        align="center"
        label="最后更新时间"
        :formatter="tableTimeFormatter"
      >
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作"
      >
        <template slot-scope="scope">
          <!-- <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">修改</el-button> -->
          <!-- <el-button type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button> -->

          <el-button
            v-if="scope.row.orderStatus == 1"
            type="text"
            size="small"
            @click="handleAcceptOrder(scope.row.id)"
            >接单</el-button
          >
          <el-button
            v-if="scope.row.orderStatus == 1"
            type="text"
            size="small"
            @click="handleRefuseOrder(scope.row.id)"
            >拒绝</el-button
          >
          <el-button
            v-if="scope.row.orderStatus == 2 || scope.row.orderStatus == -2"
            type="text"
            size="small"
            @click="handleDeliveryOrder(scope.row.id)"
            >配送</el-button
          >

          <el-button
            v-if="scope.row.orderStatus == -2"
            type="text"
            size="small"
            @click="handleCancelOrder(scope.row.id)"
            >确认取消</el-button
          >

          <el-button
            v-if="scope.row.orderStatus == 3"
            type="text"
            size="small"
            @click="handleSendedOrder(scope.row.id)"
            >送达</el-button
          >

          <el-button
            v-if="scope.row.orderStatus > 2"
            type="text"
            size="small"
            @click="goRoute(`/#/sys-deliverylog?orderSn=${scope.row.orderSn}`)"
            >查看配送记录</el-button
          >

          <el-button
            v-if="scope.row.orderStatus > -1 && scope.row.orderStatus <= 3"
            type="text"
            size="small"
            @click="handleCancelOrder(scope.row.id)"
            >取消</el-button
          >

          <el-button
            v-if="scope.row.confirmStatus == 1"
            type="text"
            size="small"
            @click="showComment(scope.row.orderSn)"
            >查看评论</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdate"
      @refreshDataList="getDataList"
    ></add-or-update>

    <!-- 订单详情 对话框 -->
    <el-dialog
      title="订单详情"
      :visible.sync="showDetailDialogVisible"
      width="70%"
      center
    >
      <el-table :data="orderItems" empty-text="无">
        <el-table-column
          property="productName"
          label="商品名"
          width="150"
          align="center"
        ></el-table-column>
        <el-table-column
          property="num"
          label="数量"
          width="60"
          align="center"
        ></el-table-column>
        <el-table-column
          property="saleAttrValueArray"
          label="销售属性"
          width="230"
          show-overflow-tooltip
          align="center"
        ></el-table-column>
        <el-table-column
          property="basePrice"
          label="商品基础价格"
          align="center"
        ></el-table-column>
        <el-table-column
          property="saleAttrExtraPrice"
          label="销售属性额外价格"
          width="150"
          align="center"
        ></el-table-column>
        <el-table-column
          property="couponAmount"
          label="优惠"
          align="center"
        ></el-table-column>
        <el-table-column
          property="realAmount"
          label="实付价格"
          align="center"
        ></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import AddOrUpdate from './order-add-or-update'
export default {
  data () {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      dataForm: {
        key: ''
      },
      query: {
        orderStatus: '',
        orderConfirmStatus: '',
        startAndEndTime: ''
      },
      // 订单项数据
      orderItems: [],
      showDetailDialogVisible: false,
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false
    }
  },
  components: {
    AddOrUpdate
  },
  activated () {
    // 如果url参数中有orderSn
    const queryOrderSn = this.$route.query.orderSn
    if (queryOrderSn) {
      this.dataForm.key = queryOrderSn
    }

    this.getDataList()
  },
  methods: {
    // 查看订单是否有评论
    async checkHasComment (orderSn) {
      let flag = false

      await this.$http({
        url: this.$http.adornUrl(`/comment/all?orderSn=${orderSn}`),
        method: 'get'
      }).then(({ data }) => {
        if (data && data.code === 0) {
          if (data.data) {
            flag = true
            console.log(`有评论:${orderSn}`, flag)
          }
        } else {
          this.$message.error(data.msg)
        }
      })
      return flag
    },
    async showComment (orderSn) {
      let flag = await this.checkHasComment(orderSn)

      console.log('flag', flag)
      if (flag) {
        this.goRoute(`/#/sys-comment?orderSn=${orderSn}`)
      } else {
        this.$message.error('该订单暂时没有评论')
      }
    },
    // 送达
    handleSendedOrder (id) {
      this.handleOrderOperation(id, 'confirmsended', '送达')
    },
    // 取消订单
    handleCancelOrder (id) {
      this.handleOrderOperation(id, 'cancel', '取消')
    },
    // 接单
    handleAcceptOrder (id) {
      this.handleOrderOperation(id, 'accept', '接单')
    },
    // 配送
    handleDeliveryOrder (id) {
      this.handleOrderOperation(id, 'delivery', '配送')
    },
    // 拒绝订单
    handleRefuseOrder (id) {
      this.handleOrderOperation(id, 'refuse', '拒绝')
    },
    // 通用的订单操作
    handleOrderOperation (id, operationCode, operationName) {
      this.$confirm(`确定对[id=${id}]进行${operationName}操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl(`/order/${id}/${operationCode}`),
          method: 'post'
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: `${operationName}成功`,
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    },

    // 查看订单明细
    async showOrderDetail () {
      let orderSnList = this.dataListSelections.map((item) => {
        return item.orderSn
      })
      console.log(orderSnList)
      await this.getOrderItems(orderSnList[0])

      this.showDetailDialogVisible = true
    },
    getOrderItems (orderSn) {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl(`/orderitem/${orderSn}/all`),
        method: 'get'
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.orderItems = data.data
        } else {
          this.orderItems = []
        }
        this.dataListLoading = false
      })
    },
    // 获取数据列表
    getDataList () {
      console.log(this.query.startAndEndTime)
      // 时间格式化
      let startTime = ''
      let endTime = ''
      if (this.query.startAndEndTime) {
        startTime = this.query.startAndEndTime[0].format('yyyy-MM-dd HH:mm:ss')
        endTime = this.query.startAndEndTime[1].format('yyyy-MM-dd HH:mm:ss')
      }

      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/order/list'),
        method: 'get',
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          key: this.dataForm.key,
          orderStatus: this.query.orderStatus,
          orderConfirmStatus: this.query.orderConfirmStatus,
          startTime: startTime,
          endTime: endTime
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle (val) {
      this.dataListSelections = val
    },
    // 新增 / 修改
    addOrUpdateHandle (id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id)
      })
    },
    // 删除
    deleteHandle (id) {
      var ids = id
        ? [id]
        : this.dataListSelections.map((item) => {
          return item.id
        })
      this.$confirm(
        `确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        this.$http({
          url: this.$http.adornUrl('/order/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    }
  }
}
</script>
